/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef HMSERIALIZATION_YYJSON_UTIL_H
#define HMSERIALIZATION_YYJSON_UTIL_H

#include <memory>
#include "yyjson.h"
#include "napi/native_api.h"

namespace yyjson_util {
struct yyjson_doc_deleter {
    void operator()(yyjson_doc *doc) const {
        if (doc) {
            yyjson_doc_free(doc);
        }
    }
};

struct yyjson_incr_state_deleter {
    void operator()(yyjson_incr_state *state) const {
        if (state) {
            yyjson_incr_free(state);
        }
    }
};

struct yyjson_mut_doc_deleter {
    void operator()(yyjson_mut_doc *mdoc) const {
        if (mdoc) {
            yyjson_mut_doc_free(mdoc);
        }
    }
};

struct FreeDeleter {
    void operator()(char* p) const noexcept {
        free(p);
    }
};

using unique_yyjson_doc = std::unique_ptr<yyjson_doc, yyjson_doc_deleter>;

using unique_yyjson_incr_state = std::unique_ptr<yyjson_incr_state, yyjson_incr_state_deleter>;

using unique_yyjson_mut_doc = std::unique_ptr<yyjson_mut_doc, yyjson_mut_doc_deleter>;

bool is_valid_integer(const char *val, size_t len);

char *add_prefix(const char *key_str, size_t len);

napi_value yyjson_to_napi(struct napi_env__ *env, yyjson_val *val);

yyjson_mut_val* napi_to_yyjson(napi_env env, yyjson_mut_doc* doc, napi_value value);
}

#endif //HMSERIALIZATION_YYJSON_UTIL_H
